package com.bidevalution.controller.api;

import com.bidevalution.business.context.UserRoleType;
import com.bidevalution.business.service.*;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.controller.vo.BeSectionMethodVO;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionProgress;
import com.bidevalution.dao.entity.ProjectInfo;
import com.bidevalution.dao.mapper.ProjectInfoMapper;
import com.bidevalution.service.EntInfoService;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.SectionStateEnum;
import com.chatroom.api.constant.MemberDisplay;
import com.chatroom.api.constant.MemberType;
import com.chatroom.api.dto.ChatGroupInfoDTO;
import com.chatroom.api.dto.ChatGroupMemberDTO;
import com.chatroom.api.service.ChatGroupInfoApiService;
import com.chatroom.api.service.ChatGroupMemberApiService;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.common.core.ContextHolderUtils;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Paging;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.OConvertUtils;
import com.qtp.core.util.ParamsUtil;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 获取标段数据控制层
 *
 * @author shenhui
 */
@Log4j2
@RestController
@RequestMapping("/beSectionInfo")
@Api(description = "标段信息相关操作Controller")
public class BeSectionInfoController extends BaseController {
    @Autowired
    private BeSectionInfoService beSectionInfoService;
    @Autowired(required = false)
    private EnterPriseInfoDubboService enterPriseInfoDubboService;
    @Autowired
    private BeSectionProgressService beSectionProgressService;
    @Autowired
    private BeNoticeDataService beNoticeDataService;
    @Autowired
    private ChatGroupMemberApiService chatGroupMemberApiService;
    @Autowired
    private ChatGroupInfoApiService chatGroupInfoApiService;
    @Autowired
    private SmsSendService smsSendService;
    @Value("${SystemIdentify}")
    private String appKey;
    @Value("${IS_CALL_INTERFACE}")
    private String isCallInterface;
    @Autowired
    private EntInfoService entInfoService;
    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    private Logger logger = Logger.getLogger(getClass());

    /**
     * 分页查询，获取开标列表信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getBeSectionListPaging", method = RequestMethod.POST)
    @ResponseBody
    public void getBeSectionListPaging(HttpServletRequest request, HttpServletResponse response) {
        // log.debug("getBeSectionListPaging**********************");
        setHttpServletResponse(response);
        TSUser tsUser = getTSUser();
        try {
            // 获取请求中的参数
            Map<String, Object> paramsMap = ParamsUtil.getParamsObjValue(request, "type,sectionName,page,rp");
            // 添加是否企业用户
            paramsMap.put("isEnterUserType", isEnterUserType(tsUser));
            // 添加企业id
            paramsMap.put("enterpriseId", tsUser.getOrgId());
            Paging<List<BeSectionInfo>> btnResponse = beSectionInfoService.getBeSectionListPaging(paramsMap);
            long total = btnResponse.getTotal();
            ContextHolderUtils.outGridJson(response, btnResponse.getData(), total, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 查询所有标段信息
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getBeSectionAllPaging", method = RequestMethod.GET)
    public void getBeSectionAllPaging(HttpServletRequest request, HttpServletResponse response) {
        setHttpServletResponse(response);
        TSUser tsUser = getTSUser();
        try {
            // 获取请求中的参数
            Map<String, Object> paramsMap = ParamsUtil.getParamsObjValue(request, "sectionName,page,rp");
            // 添加企业id
            paramsMap.put("enterpriseId", tsUser.getOrgId());
            Paging<List<BeSectionInfo>> btnResponse = beSectionInfoService.getAllList(paramsMap);
            long total = btnResponse.getTotal();
            ContextHolderUtils.outGridJson(response, btnResponse.getData(), total, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 根据主键获取标段信息
     *
     * @param seqId
     * @return
     */
    @ApiOperation(value = "标段信息相关操作--根据标段主键获取标段详细信息(2019-09-17-v1)", response = BeSectionInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seqId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @RequestMapping(value = "/getSignSectionInfoById", method = RequestMethod.GET)
    @ResponseBody
    public Response<BeSectionInfo> getBeSectionInfoById(@RequestParam("seqId") String seqId) {
        if (StringUtils.isBlank(seqId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        return Response.ok(beSectionInfoService.getBeSectionInfoById(seqId));
    }

    /**
     * 获取服务器时间
     *
     * @return
     */
    @RequestMapping(value = "/getServerTime", method = RequestMethod.GET)
    @ResponseBody
    public Response<String> getServerTime() {
        Date datetime = DateUtil.now();
        String dateStr = DateUtil.dateToString(datetime, DateUtil.PT2);
        return Response.ok(dateStr);
    }

    /**
     * 获取用户角色
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getUserRole", method = RequestMethod.GET)
    public Response<String> getEcUserRole(HttpServletRequest request, HttpServletResponse response) {
        setHttpServletResponse(response);
        TSUser loginUser = getTSUser();
        try {
            List<String> roles = getUserRole(loginUser);
            return Response.ok(StringUtils.join(roles, ","));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 更新标段状态
     *
     * @param sectionId
     * @return
     */
    @RequestMapping(value = "/updateSectionStage", method = RequestMethod.POST)
    @ResponseBody
    public Response<Boolean> updateSectionStage(@RequestParam("sectionId") String sectionId,
                                                @RequestParam("sectionStage") String sectionStage) {
        try {
            // log.debug("******************updateSectionStage");
            boolean result = beSectionInfoService.updateSectionStage(sectionId, sectionStage);
            if (result) {
                //发送短信
                smsSendService.sendBidFlowMsg(sectionId, sectionStage);
                // 添加系统公告
                beNoticeDataService.addNotice(sectionId, sectionStage);
            }
            if (beSectionProgressService.selectByKey(sectionId, sectionStage) == null) {
                BeSectionProgress beSectionProgress = new BeSectionProgress();
                if ("1".equals(sectionStage)) {
                    BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
                    beSectionProgress.setCreateTime(beSectionInfo.getBidOpenTime());
                } else {
                    beSectionProgress.setCreateTime(new Date());
                }
                //防止bided状态没有执行成功，则下一步继续执行
                if (SectionStateEnum.bided.getValue().equals(sectionStage)
                        || SectionStateEnum.paramdrawing.getValue().equals(sectionStage)) {
                    // 解密已经完成进入到后面状态
                    logger.info("投标人更新状态");
                    ChatGroupInfoDTO chatGroupInfoDTO = chatGroupInfoApiService.getByBusinessGroupId(appKey,
                            sectionId);
                    if (chatGroupInfoDTO != null) {
                        List<ChatGroupMemberDTO> dataList = chatGroupMemberApiService.getMemberList(appKey,
                                chatGroupInfoDTO.getGroupId(), null);
                        // 显示所有投标用户为可见
                        for (ChatGroupMemberDTO chatGroupMemberDTO : dataList) {
                            chatGroupMemberApiService.updateMember(appKey, chatGroupInfoDTO.getGroupId(),
                                    chatGroupMemberDTO.getUserId(),
                                    MemberType.getMemberType(chatGroupMemberDTO.getMemberType()),
                                    MemberDisplay.Visible);
                        }
                        for (ChatGroupMemberDTO chatGroupMemberDTO : dataList) {
                            if (chatGroupMemberDTO.getMemberType() >= MemberType.thirdManager.getCode()) {
                                chatGroupMemberApiService.refreshUser(appKey, sectionId,
                                        chatGroupMemberDTO.getUserId());
                            }
                        }
                    }
                }

                beSectionProgress.setSectionId(sectionId);
                beSectionProgress.setState(sectionStage);
                beSectionProgressService.insert(beSectionProgress);
            }
            return Response.ok(result);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail("更新标段状态失败");
        }
    }

    /**
     * 根据单位ID 获得单位信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getEnterpriseInfoById", method = RequestMethod.POST)
    public Response getEnterpriseInfoById() {
        try {
            TSUser loginUser = getTSUser();
            Map<String, Object> params = new HashMap<>();
            params.put("ep_guid", loginUser.getOrgId());
            // 获取请求中的参数
            return enterPriseInfoDubboService.getEnterInfo(params);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 获得当前账号在当前项目中的角色信息
     *
     * @param sectionId 标段id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserRoleType", method = RequestMethod.GET)
    public Response<String> getUserRoleType(@RequestParam("sectionId") String sectionId) {
        try {
            TSUser loginUser = getTSUser();
            List<String> roleList = getUserRole(loginUser);
            UserRoleType userRoleType = beSectionInfoService.getUserRoleType(sectionId, loginUser, roleList);
            if (userRoleType == null) {
                return Response.fail("用户类型不存在");
            }
            return Response.ok(userRoleType.getValue());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }


    /**
     * 获取招标代理今日评审项目列表
     *
     * @param sectiName
     * @param sectiCode
     * @param startTime
     * @param endTime
     * @return
     */
    @ApiOperation(value = "标段信息相关操作--获取招标代理今日评审项目列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectiName", value = "标段名称", dataType = "String", paramType = "query", example = ""),
            @ApiImplicitParam(name = "sectiCode", value = "标段编号", dataType = "String", paramType = "query", example = ""),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query", example = "2019-08-01"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query", example = "2019-08-07"),
    })
    @GetMapping(value = "/getAgentSectionList")
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "用户未登录，请登录！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "您所在企业未在企业库进行注册！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "企业组织机构代码为空！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_FOUR, message = "系统错误，请联系管理员！"),
    })
    public Response getAgentSectionList(HttpServletRequest request, @RequestParam(value = "sectiName", required = false) String sectiName,
                                        @RequestParam(value = "sectiCode", required = false) String sectiCode, @RequestParam(value = "startTime", required = false) String startTime,
                                        @RequestParam(value = "endTime", required = false) String endTime) {
        String userGuid = request.getHeader("userGuid");
        TSUser loginUser = RedisAccess.getValue(TSUser.class, userGuid);
        if (loginUser == null) {
            return Response.fail("用户未登录，请登录！", Constants.FIVE_HUNDRED_AND_ONE);
        }
        Map<String, Object> paramsMap = new HashMap<>(8);
        paramsMap.put("ep_guid", loginUser.getOrgId());
        try {
            //获取当前登录用户组织机构代码
            Map<String, Object> enterResult = (Map<String, Object>) enterPriseInfoDubboService.getEnterInfo(paramsMap).getResult();
            if (enterResult.isEmpty()) {
                return Response.fail("您所在企业未在企业库进行注册！", Constants.FIVE_HUNDRED_AND_TWO);
            }
            String orgCode = OConvertUtils.getString(enterResult.get("ep_org_code"));
            if (StringUtils.isBlank(orgCode)) {
                return Response.fail("企业组织机构代码为空！", Constants.FIVE_HUNDRED_AND_THREE);
            }
            // 参数组装
            paramsMap.put("sectiName", sectiName);
            paramsMap.put("sectiCode", sectiCode);
            paramsMap.put("orgCode", orgCode);
            paramsMap.put("startTime", startTime);
            paramsMap.put("endTime", endTime);
            return Response.ok(beSectionInfoService.getAgentSectionList(paramsMap));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail("系统错误，请联系管理员！", Constants.FIVE_HUNDRED_AND_FOUR);
        }
    }

    /**
     * 获取专家今日评审项目列表
     *
     * @return
     */
    @ApiOperation(value = "标段信息相关操作--获取专家今日评审项目列表", response = BeSectionInfo.class)
    @GetMapping(value = "/getExpertSectionList")
    public Response getExpertSectionList(HttpServletRequest request) {
        try {
            String userGuid = request.getHeader("userGuid");
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if(tsUser != null) {
                return Response.ok(beSectionInfoService.getExpertSectionList(tsUser.getLoginName()));
            } else {
                return Response.fail("获取专家账号登录信息失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail("专家今日评审项目列表获取失败");
        }
    }
    /**
     * 获取专家今日评审项目列表
     *
     * @return
     */
    @ApiOperation(value = "标段信息相关操作--获取所有项目列表", response = BeSectionInfo.class)
    @GetMapping(value = "/getAllSectionList")
    public Response<List<BeSectionInfo>> getAllSectionList(String areaId,String sectionName,String sectionCode) {
        try {
        	String userGuid = RequestUtil.getHeader("userGuid");
            TSUser loginUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (loginUser == null) {
                return Response.fail("用户未登录，请登录！", Constants.FIVE_HUNDRED_AND_ONE);
            }
            Map<String, Object> paramsMap = new HashMap<>(8);
            paramsMap.put("ep_guid", loginUser.getOrgId());
        	 //获取当前登录用户组织机构代码
            Map<String, Object> enterResult = (Map<String, Object>) enterPriseInfoDubboService.getEnterInfo(paramsMap).getResult();
            if (enterResult.isEmpty()) {
                return Response.fail("您所在企业未在企业库进行注册！", Constants.FIVE_HUNDRED_AND_TWO);
            }
            String orgCode = OConvertUtils.getString(enterResult.get("ep_org_code"));
            if (StringUtils.isBlank(orgCode)) {
                return Response.fail("企业组织机构代码为空！", Constants.FIVE_HUNDRED_AND_THREE);
            }
        	return Response.ok(beSectionInfoService.getAllSectionList(orgCode,areaId, sectionName, sectionCode));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Response.fail("获取所有项目列表失败");
        }
    }

    @ApiOperation(value = "标段信息相关操作--代理点击评审开始的更新操作(2019-11-11-v1)", response = String.class)
    @PostMapping(value = "/updateReviewStart")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "sectionId", value = "标段主键", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "数据更新失败，请联系管理员！"),
    })
    public Response<String> updateReviewStart(@RequestParam(value = "sectionId") String sectionId) {
        Response<String> msg;
        try {
            if (StringUtils.isBlank(sectionId)) {
                return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
            }
            //是否调用接口(Y、是 N、否)
            if (Constants.TRUE.equals(isCallInterface)) {
                BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
                //触发招标保证金获取接口
                msg = entInfoService.getZbDeposit(beSectionInfo.getSectionCode());
                if (Constants.FIVE_HUNDRED == msg.getStatus()) {
                    logger.info("标段[" + beSectionInfo.getSectionName() + "]获取招标保证金错误信息：" + msg.getError());
                }
                //触发投标保证金获取接口
                msg = entInfoService.getTbDeposit(beSectionInfo.getSectionCode());
                if (Constants.FIVE_HUNDRED == msg.getStatus()) {
                    logger.info("标段[" + beSectionInfo.getSectionName() + "]获取投标单位保证金错误信息：" + msg.getError());
                }
                //触发企业资质获取接口
                entInfoService.getEnpriseCheck(beSectionInfo.getSectionCode());
//                if (Constants.FIVE_HUNDRED == msg.getStatus()) {
//                    logger.info("标段[" + beSectionInfo.getSectionName() + "]获取投标单位企业资质错误信息：" + msg.getError());
//                }
            }
            //更新操作
            msg = beSectionInfoService.updateReviewStart(sectionId);
            if (Constants.FIVE_HUNDRED == msg.getStatus()) {
                return Response.fail(msg.getError());
            }
            return Response.ok("设置评标开始成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail("操作失败，请联系管理员！", Constants.FIVE_HUNDRED_AND_TWO);
        }
    }

    @ApiOperation(value = "获取工程概况信息", response = String.class)
    @GetMapping(value = "/getProjectInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "projectId", value = "项目ID", required = true),
    })
    public Response<ProjectInfo> getProjectInfo(@RequestParam(value = "projectId") String projectId) {
        if(StringUtils.isBlank(projectId)) {
            return Response.fail("项目ID不能为空");
        }
        ProjectInfo projectInfo = projectInfoMapper.getProjectInfo(projectId);
        if(projectInfo == null) {
            return Response.fail("没有查询到工程概况信息");
        }
        return Response.ok(projectInfo);
    }
    @PostMapping("/deleteBySectionId")
    @ApiOperation(value = "删除标段方法信息", notes = "删除标段方法信息", response = BeSectionMethodVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query") })
    public Response deleteBySectionId(String sectionId) {
        return beSectionInfoService.deleteBySectionId(sectionId);
    }
    @PostMapping("/deleteEnterprise")
    @ApiOperation(value = "删除标段方法信息", notes = "删除标段方法信息", response = BeSectionMethodVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "enterpriseId", value = "企业ID", required = true, dataType = "String", paramType = "query")})
    public Response deleteEnterprise(String sectionId, String enterpriseId) {
        return beSectionInfoService.deleteEnterprise(sectionId, enterpriseId);
    }
}
